# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '95390': {
        # <通道>: LIMAFUPAY  <支付方式>:alipay wap或h5 <限额>：最低金额 50； 每小时限额 30000； 最大金额 5000；
        # <产品>: loki <费率>: 2.5
        'API_KEY': 'FsyuWSZ1jfuO84lq59eSYtbaZOjRFNS3',
        'gateway': 'http://api.ponypay1.com/',
        'query_gateway': 'http://api.ponypay1.com/search.aspx',
    },
    '95431': {
        # 立马付 支付宝H5 2.5% 10-10000 dwc
        # 'API_KEY': 'zXWcPtxZ0JmZA3aNCJKM673g6fX59gtDzjJSDJ96mjJfpqxjJNpNWPa2JktNwN30',
        'API_KEY': 'WYRqMJLIBW2eJAT5TtdOQf781qz2nWfh',
        'gateway': 'http://api.ponypay1.com/',
        'query_gateway': 'http://api.ponypay1.com/search.aspx',
    },
    '95495': {
        # 立马付 支付宝H5 2.5% 10-10000 witch
        'API_KEY': '0717480760725395707564207680751957845634614707358078232324107207',
        'gateway': 'http://api.ponypay1.com/',
        'query_gateway': 'http://api.ponypay1.com/search.aspx',
    },
    '95494': {
        # 立马付 支付宝H5 2.5% 10-10000 zs
        'API_KEY': '1307218527616923078789652307676307216387898123438763452343678521',
        'gateway': 'http://api.ponypay1.com/',
        'query_gateway': 'http://api.ponypay1.com/search.aspx',
    },
    '95493': {
        # 立马付 支付宝H5 2.5% 10-10000 tt
        'API_KEY': '4727272727272727272727272727272727272717272717271717271737271737',
        'gateway': 'http://api.ponypay1.com/',
        'query_gateway': 'http://api.ponypay1.com/search.aspx',
    },
    '95515': {
        # 立马付 云闪付 1.6% 10-5000 dwc
        'API_KEY': '4693828430769078321563479352381436564134078312727128126257073850',
        'gateway': 'http://api.ponypay1.com/',
        'query_gateway': 'http://api.ponypay1.com/search.aspx',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(parameter, key):
    s = ''
    key_list = ['merchant_id', 'orderid', 'paytype', 'notifyurl', 'callbackurl', 'money']
    new_dict = OrderedDict((k, parameter.get(k)) for k in key_list)
    for k in new_dict:
        if k != 'sign' and new_dict[k] is not None:
            s += '%s' % new_dict[k]
    s += '%s' % key
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.lower() != calculated_sign.lower():
        _LOGGER.info("limafupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return 'ZFB'
    elif service == 'alipayh5':
        return 'ZFBH5'
    elif service == 'wechat_scan':
        return 'WX'
    elif service == 'wechat_wap':
        return 'WXH5'
    elif service == 'cloud_flash':
        return 'YSF'
    return 'ZFB'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchant_id', app_id),
        ('orderid', str(pay.id)),
        ('paytype', _get_pay_type(service)),
        ('bankcode', ''),
        ('notifyurl', '{}/pay/api/{}/limafupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('callbackurl', '{}/pay/api/{}/limafupay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('userip', _get_device_ip(info)),
        ('money', '%.2f' % pay_amount),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("limafupay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['orderid'])
    headers = {"Content-type": "application/x-www-form-urlencoded"}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info('limafupay create rsp, %s', response.text)
    return {'charge_info': json.loads(response.text)['data']['url']}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)

    data = dict(request.GET.iteritems())
    _LOGGER.info("limafupay notify data is: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['orderid']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('limafupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    total_fee = float(data['money'])
    trade_no = str(data['orderid'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 0 未处理 1 交易成功 2 支付失败 3 关闭交易 4 支付超时
    if trade_status == '1' and total_fee > 0.0:
        _LOGGER.info('limafupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchant_id', app_id),
        ('orderid', str(pay_order.id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('limafupay query data: %s, order_id is: %s', json.dumps(parameter_dict), str(pay_order.id))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info('limafupay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        _LOGGER.info("limafupay query response body: %s", data)
        mch_id = pay_order.mch_id
        trade_status = str(data['data']['status'])
        total_fee = float(data['data']['money'])
        trade_no = ''
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        if trade_status == '3':
            pay_id = data['data']['orderid']
            check_channel_order(pay_id, total_fee, app_id)
            _LOGGER.info('limafupay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
